/*
 * @Author: aggfb 714740235@qq.com
 * @Date: 2024-04-22 21:39:52
 * @LastEditors: aggfb 714740235@qq.com
 * @LastEditTime: 2024-06-08 15:49:11
 * @FilePath: \label_rack_control\firmware\model\motor_ctrl\motor_ctrl.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include "motor_ctrl.h"
#include "SEGGER_RTT.h"
#include "bsp_timer.h"

static motor_ctrl_t motor_ctrl ={
    .speed_ratio_cmd = 0,   /* 速度默认一档 */
    .manual_automatic = MOTOR_CTRL_MATNUAL,  /* 模式默认手动 */
};

/**
 * 电机控制设备
 */
motor_ctrl_t* motor_ctrl_dev(void)
{
    return (&motor_ctrl);
}

/**
 * 设置电机运行
 * uint8_t dir : 方向
 * uint32_t step : 步数
 */
void motor_ctrl_running(uint8_t repetition, uint8_t dir, uint16_t speed, uint16_t step)
{
    if (dir > 1)
        dir = 1;
    if(speed < MOTOR_SPEED_MAX)
        speed = MOTOR_SPEED_MAX;
    else if(speed > MOTOR_SPEED_MIN)
        speed = MOTOR_SPEED_MIN;
    
    speed = (MOTOR_SPEED_MIN + 1) - speed;
    uint16_t pwm_val = speed * 10;

    BSP_GPIO_SET_MOTOR_ENA(0);
    BSP_GPIO_SET_MOTOR_DIR(dir);
    bsp_delay_us(5);
    bsp_timer31_pulse_output(repetition, pwm_val, step);
}

/**
 * 设置电机停止
 * uint8_t dir : 方向
 * uint32_t step : 步数
 */
void motor_ctrl_stop(void)
{
    BSP_GPIO_SET_MOTOR_ENA(1);
    bsp_timer31_pulse_output(0, 0, 0);
}

/**
 * 从定时器中断
*/

void TMR1_UP_IRQHandler(void)
{
    if(TMR_ReadIntFlag(TMR1, TMR_INT_UPDATE) == SET)
    {
        TMR_ClearIntFlag(TMR1, TMR_INT_UPDATE);
        motor_ctrl_stop();
        motor_ctrl.flag_trig = 1;
    }
}
